from piston.handler import BaseHandler
import datetime
from django.utils import simplejson
from django.core.files import File
from django.core.files.base import ContentFile

from models import Users
from models import SocialAccount
from models import Message

class RegisterHandler(BaseHandler):

		@classmethod
		def read( self, request, querystring ):
			return "register read"
		
		@classmethod
		def create( self, request, querystring ):
				try:
					json_data = simplejson.loads(request.raw_post_data)
					#check it is existing
					
					record = Users.objects.filter(email=json_data['email'])
					if len(record) > 0:
						return 'FAILED'
					else:
						new_user = Users(
						first_name = json_data['first_name'],
						last_name = json_data['last_name'],
						email = json_data['email'],			
						password = json_data['password']
						)
						new_user.save()
						objects = Users.objects.get(email=json_data['email'])
						objects = UtilityHandler.produceJSON(objects)
						return objects
				except:
					return 'FAILED'
		
			
class LoginHandler( BaseHandler):
		allow_method =('GET', 'POST','PUT', 'DELETE')
		
		#for GET method
		@classmethod
		def read( self, request, querystring ):
				#LoginHandler.saveNewUser()
				try:
					emailaddr=request.GET.get('email')
					pwds=request.GET.get('password')
					objects = Users.objects.get(email=emailaddr, password=pwds)

					#objects = record.all()
					objects = UtilityHandler.produceJSON(objects)

					#objects = [LoginHandler.produceJSON(o)   #for the result is a list of JSON
          #          for o in objects ]
					#if len(objects) == 1:
					#	objects = objects[0]
				except:
					return 'FAILED'
				else:
					return objects
		
		#for POST method
		@classmethod
		def create( self, request, querystring):
				try:
					json_data = simplejson.loads(request.raw_post_data)
					#check it is existing
					record = Users.objects.filter(email=json_data['email'])
					if len(record) > 0:
						return 'FAILED'
					else:
						new_user = Users(
						first_name = json_data['first_name'],
						last_name = json_data['last_name'],
						email = json_data['email'],			
						password = json_data['password']
						)
						new_user.save()
						objects = Users.objects.get(email=json_data['email'])
						objects = LoginHandler.produceJSON(objects)
						return objects
				except:
					return 'FAILED'


#User profiler handler
class ProfileHandler( BaseHandler):

		@classmethod
		def read( self, request, querystring ):
				try:
					userid=request.GET.get('uid')
					object = Users.objects.get(id=userid)

					#objects = record.all()
					object = UtilityHandler.produceJSON(object)

				except:
					return 'FAILED'
				else:
					return object
					
		#for PUT method, define update method
		@classmethod
		def update( self, request, querystring):
				try:
					json_data = simplejson.loads(request.raw_post_data)
					record = Users.objects.get(id=json_data['uid'])
					
					record.email = json_data['email']
					record.password = json_data['password']
					#other fields needs to be updated

					record.save()
				except:
					#need to know exception type
					record.save()
				finally:
					return UtilityHandler.produceJSON(record)
				
		#for DELETE method, define delete method
		@classmethod
		def delete(self, request, querystring):
				emailaddr=request.GET.get('email')
				record = Users.objects.get(email=emailaddr)
				
				record.delete()
				return

#User profile image update handler
class ProfileImageHandler( BaseHandler):

		@classmethod
		def read( self, request, querystring ):
			return "profile image read"
			
		@classmethod
		def create(self, request, querystring):
				try:
					json_data = simplejson.loads(request.data['postData'])
					record = Users.objects.get(id=json_data['uid'])
					f = request.FILES['profile']
					image_name = f.name
					record.profile = f     #store image in the document
					record.profile.content_type = 'image/jpeg'
					record.save()
					#UtilityHandler.saveFile(record.profile)
				except Exception as e:
					return 'FAILED'
				else:
					return 'SUCCEED'
    		
    		
#User profile search handler(may return a list of matched json)
class ProfileSearchHandler( BaseHandler):

		@classmethod
		def read( self, request, querystring ):
				try:
					userid = request.GET.get('uid')
					emailaddr = request.GET.get('email')
					edu = request.GET.get('education')

					if userid != None:
						objects = Users.objects.filter(id=userid)
					elif emailaddr != None:
						objects = Users.objects.filter(email=emailaddr)
					elif edu != None:
						objects = Users.objects.filter(education=edu)
						
					objects = [UtilityHandler.produceJSON(o)   #for the result is a list of JSON
                    for o in objects ]
					if len(objects) == 1:
						objects = objects[0]

				except:
					return 'FAILED'
				else:
					return objects




#General utitlity class used for other classes				
class UtilityHandler( BaseHandler):					
		@staticmethod
		def produceJSON(retobj):
			retval = {}
			retval['uid'] = retobj['id']
			retval['first_name'] = retobj['first_name']
			retval['last_name'] = retobj['last_name']
			retval['email'] = retobj['email']
			retval['password'] = retobj['password']
			return retval
			
		@staticmethod
		def saveNewUser():
			new_user=Users(
				first_name="yang",
				last_name="lu",
				password="123",
				email="yang@cmu.edu",
				education="CMU", 
				credit_score=0.0, 
				friend_list=[0],
				group_list=[0],
				socialnetwork_account=[
				SocialAccount
				(
					network_type="linkedIn",
					username="lu",
					password="123"
				)
				],
				messagebox=[
				Message
				(
					sender_email="kai@cmu.edu",
					receiver_email="yang@cmu.edu",
					send_date=datetime.datetime.strptime("2012-04-12 15:30","%Y-%m-%d %H:%M"),
					content="hello!",
					carpool_no=0, 
					msg_type="regular", 
					msg_status="done"
				)
				]
			)
			new_user.save()
			return
			
		@staticmethod
		def saveFile(f):
			fw = open('/Users/lvyang246/Project/profile.jpg','w')
			myfile = File(fw)
			chunk = f.read()
			myfile.write(chunk)
			myfile.close()
			return